package cn.fetosoft.woodpecker.controller;

import cn.fetosoft.woodpecker.core.event.SampleResultEvent;
import cn.fetosoft.woodpecker.enums.MessageType;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 接口测试结果通知
 * @author guobingbing
 * @version 1.0
 * @wechat t_gbinb
 * @create 2021/6/24 10:10
 */
@Component
@ServerEndpoint("/auth/sample/notice/{userId}")
public class SampleResultNotice implements ApplicationListener<SampleResultEvent> {

	private static final Logger logger = LoggerFactory.getLogger(PlanResultNotice.class);
	private static final Map<String, Session> SESSION_MAP = new HashMap<>();

	@OnOpen
	public void connect(@PathParam("userId") String userId, Session session){
		try {
			SESSION_MAP.put(userId, session);
			session.getBasicRemote().sendText(new SocketMessage(MessageType.ConnSuccess, "Conn success").toString());
		} catch (IOException e) {
			logger.error("connect", e);
		}
	}

	@OnClose
	public void disconnect(Session session){
		this.destroy(session);
	}

	@OnError
	public void errorHandle(Throwable e, Session session){
		this.destroy(session);
		logger.error("onError", e);
	}

	private void destroy(Session session){
		if(session!=null && session.isOpen()){
			try {
				session.close();
			} catch (IOException e) {
				logger.error("destroy", e);
			}
		}
	}

	private void sendText(String userId, String text){
		Session session = SESSION_MAP.get(userId);
		if(session!=null && session.isOpen()){
			try {
				session.getBasicRemote().sendText(text);
			} catch (IOException e) {
				logger.error("sendText", e);
			}
		}
	}

	@Override
	public void onApplicationEvent(SampleResultEvent event) {
		SocketMessage message = new SocketMessage(MessageType.TestComplete, "testComplete");
		this.sendText(event.getUserId(), message.toString());
	}
}
